package com.web.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",filterName = "authenticationFilter")
public class AuthenticationFilter implements Filter {

    private static Logger LOG = LoggerFactory.getLogger(AuthenticationFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)servletRequest;
        if ( isCommondRequest(request) ) {
            LOG.info("公共资源: " + request.getRequestURI());
        } else {
            LOG.info("受保护资源: " + request.getRequestURI());
        }

        String uri = request.getRequestURI();
        String context = request.getContextPath();

        if ( context.equalsIgnoreCase(uri)
                || context.concat("/").equalsIgnoreCase(uri) ) {
            HttpServletResponse res = (HttpServletResponse)servletResponse;
            res.sendRedirect(context + "/index.html");
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }



    }

    private boolean isCommondRequest(HttpServletRequest request) {

        String contextPath = request.getContextPath();

        String uri = request.getRequestURI().replace(contextPath, "");

        if ( uri.equalsIgnoreCase("/kaptcha")
                || uri.equalsIgnoreCase("/login.html")
                || uri.equalsIgnoreCase("/platform/login") )  {
            return true;
        }

        if ( uri.startsWith("/lib/")
                || uri.startsWith("/images/")
                || uri.startsWith("/adminlte/"))  {
            return true;
        }

        if ( uri.endsWith(".css")
                || uri.endsWith(".js")  )  {
            return true;
        }
        return false;
    }

    @Override
    public void destroy() {

    }
}
